<!-- filepath: c:\Users\1\Desktop\SeekReal\src\views\Feedback.vue 2025/7/24 徐安新增反馈页面-->
<template>
  <view class="feedback-page">
    <view class="feedback-header">
      <button class="back-btn" @click="handleBackClick">← 返回</button>
      <text class="header-title">意见反馈</text>
    </view>
    <view class="feedback-form">
      <view class="form-group">
        <view>反馈类型</view>
        <picker :range="typeOptions" :value="feedbackTypeIndex" @change="onTypeChange">
          <view class="picker-view">
            {{ feedbackTypeIndex === -1 ? '请选择' : typeOptions[feedbackTypeIndex] }}
          </view>
        </picker>
      </view>
      <view class="form-group">
        <view><text class="required">*</text>反馈内容</view>
        <view class="textarea-row">
          <textarea
            v-model="content"
            :maxlength="maxLen"
            :style="{height: textareaHeight + 'px'}"
            @input="autoResize"
            
            @blur="saveDraft"
            @focus="autoResize"
            placeholder="请详细描述你的问题或建议..."
            required
          />
          <text class="char-count" :class="charCountClass">{{ content.length }}/{{ maxLen }}</text>
        </view>
        <view class="image-row">
          <text class="add-image-label">添加图片</text>
          <button type="button" class="upload-btn" @click="chooseImage" :disabled="images.length >= 3">
            <text class="upload-icon">➕</text>
          </button>
        </view>
        <view class="image-preview" v-if="images.length">
          <view v-for="(img, idx) in images" :key="idx" class="img-thumb">
            <image :src="processImageUrl(img)" mode="aspectFill" class="img-thumb-img" />
            <text class="remove-img" @click="removeImage(idx)">×</text>
          </view>
        </view>
      </view>
      <view class="form-group">
        <view>联系方式（可选）</view>
        <view class="input-icon-group">
          <text class="input-icon">{{ contactIcon }}</text>
          <input
            v-model="contact"
            :type="contactInputType"
            placeholder="邮箱/微信/手机号（选填）"
            @input="onContactInput"
            @blur="saveDraft"
          />
          
        </view>
      </view>
             <!-- 测试按钮 -->
 
       <!-- 调试信息 -->
       <!-- <view style="background: #f0f0f0; padding: 10px; margin: 10px; border-radius: 5px; font-size: 12px;">
         <text>调试信息：</text><br/>
         <text>canSubmit: {{ canSubmit }}</text><br/>
         <text>submitting: {{ submitting }}</text><br/>
         <text>按钮禁用: {{ !canSubmit || submitting }}</text><br/>
         <text>反馈类型: {{ feedbackType }}</text><br/>
         <text>内容长度: {{ content.trim().length }}</text>
       </view> -->
      
      <button class="submit-btn" @click="handleSubmitClick" @tap="handleSubmitTap" :style="{opacity: (!canSubmit || submitting) ? '0.5' : '1'}">
        <text v-if="submitting" class="loading-dot"></text>
        {{ submitting ? '提交中...' : '提交反馈' }}
      </button>
      <view v-if="successMsg" class="success-msg">{{ successMsg }}</view>
      <view v-if="errorMsg" class="error-msg">{{ errorMsg }}</view>
    </view>
  </view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, computed, watch, onMounted } from 'vue';
import { useUserStore } from '@/store/user';
import { request } from '@/utils/request';
import { processImageUrl } from '@/config/server';

const userStore = useUserStore();
const typeOptions = ['功能建议', 'BUG反馈', '其他'];
const feedbackTypeIndex = ref(-1);
const feedbackType = computed({
  get: () => feedbackTypeIndex.value === -1 ? '' : typeOptions[feedbackTypeIndex.value],
  set: val => {
    feedbackTypeIndex.value = typeOptions.indexOf(val);
  }
});
const content = ref('');
const contact = ref('');
const maxLen = 300;
const submitting = ref(false);
const successMsg = ref('');
const errorMsg = ref('');
const images = ref([]);
const textareaHeight = ref(40);
const sensitiveWords = [
  // 初始词
  '政治', '广告', '违法',
  
  // 政治相关
  '政府', '领导人', '政党', '抗议', '示威', 
  '革命', '国家机密', '军事', '领土争议',
  
  // 违法内容
  '毒品', '赌博', '诈骗', '黑客', '暴力',
  '恐怖主义', '极端主义', '淫秽', '色情',
  
  // 广告营销
  '促销', '折扣', '免费领取', '限时优惠',
  '微信号', '联系电话', '二维码', '投资理财', '加盟代理',
  
  // 其他敏感
  '宗教', '民族', '种族歧视', '性别歧视',
  '虚假信息', '隐私泄露', '自杀', '自残'
];
const ready = ref(false);

// 使用配置文件中的processImageUrl函数



const charCountClass = computed(() => {
  if (content.value.length >= maxLen) return 'count-red';
  if (content.value.length >= 200) return 'count-green';
  return 'count-gray';
});

function autoResize(e) {
  // 兼容uni-app小程序和H5
  let el = e?.target;
  if (el && el.scrollHeight) {
    let h = Math.min(el.scrollHeight, 120); // 5行约120px
    textareaHeight.value = h;
  } else {
    // fallback
    textareaHeight.value = Math.min(content.value.length / 30 * 24 + 40, 120);
  }
  saveDraft();
}

async function chooseImage() {
  uni.chooseImage({
    count: 3 - images.value.length,
    success: async res => {
      // 上传图片到后端
      const uploadedImages = [];
      for (const tempPath of res.tempFilePaths) {
        try {
          const uploadResult = await uploadImage(tempPath);
          if (uploadResult.url) {
            uploadedImages.push(uploadResult.url);
          }
        } catch (error) {
          console.error('图片上传失败:', error);
          uni.showToast({ title: '图片上传失败', icon: 'none' });
        }
      }
      images.value.push(...uploadedImages);
      saveDraft();
    }
  });
}

// 上传图片到后端
async function uploadImage(filePath) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${NETWORK_CONFIG.API_BASE_URL}/feedback/upload`,
      filePath: filePath,
      name: 'file',
      success: (res) => {
        try {
          const data = JSON.parse(res.data);
          if (data.code === 200) {
            // 处理图片URL，将HTTP转换为HTTPS（如果后端返回的是HTTP）
            if (data.url && data.url.startsWith('http://')) {
              data.url = data.url.replace('http://', 'https://');
            }
            resolve(data);
          } else {
            reject(new Error(data.message || '上传失败'));
          }
        } catch (e) {
          reject(new Error('响应解析失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}
function removeImage(idx) {
  images.value.splice(idx, 1);
  saveDraft();
}

const contactInputType = computed(() => {
  // 简单判断手机号
  if (/^1\d{0,10}$/.test(contact.value)) return 'number';
  return 'text';
});
const contactIcon = computed(() => {
  if (/^1\d{10}$/.test(contact.value)) return '📱';
  if (/^\S+@\S+\.\S+$/.test(contact.value)) return '✉️';
  return '👤';
});
function onContactInput() {
  saveDraft();
}

const canSubmit = computed(() => {
  const result = !submitting.value && feedbackType.value && content.value.trim().length >= 10;
  // console.log('📊 canSubmit 计算:', {
  //   submitting: submitting.value,
  //   feedbackType: feedbackType.value,
  //   contentLength: content.value.trim().length,
  //   result: result
  // });
  return result;
});

function saveDraft() {
  uni.setStorageSync('feedbackDraft', {
    feedbackTypeIndex: feedbackTypeIndex.value,
    content: content.value,
    contact: contact.value,
    images: images.value
  });
}

onMounted(() => {
  // console.log('🚀 页面加载完成');
  // console.log('🚀 初始状态:');
  // console.log('   - feedbackTypeIndex:', feedbackTypeIndex.value);
  // console.log('   - content:', content.value);
  // console.log('   - canSubmit:', canSubmit.value);
  
  ready.value = true;
  const draft = uni.getStorageSync('feedbackDraft');
  if (draft) {
    feedbackTypeIndex.value = draft.feedbackTypeIndex ?? -1;
    content.value = draft.content ?? '';
    contact.value = draft.contact ?? '';
    images.value = draft.images ?? [];
    // 自动调整高度
    setTimeout(() => autoResize({ target: { scrollHeight: content.value.length / 30 * 24 + 40 } }), 100);
  }
  
  // console.log('🚀 页面初始化完成');
});
watch([feedbackTypeIndex, content, contact, images], saveDraft);

function onTypeChange(e) {
  feedbackTypeIndex.value = Number(e.detail.value);
  saveDraft();
}

function hasSensitiveWords(text) {
  return sensitiveWords.some(word => text.includes(word));
}

const handleBackClick = () => {
  // console.log('🔘 返回按钮被点击了！');
  goBack();
};

const goBack = () => {
  if (content.value || contact.value || images.value.length) {
    uni.showModal({
      title: '提示',
      content: '是否放弃当前编辑？',
      success: res => {
        if (res.confirm) {
          uni.removeStorageSync('feedbackDraft');
          uni.navigateBack();
        }
      }
    });
  } else {
    
    uni.navigateBack();
  }
};

const handleSubmitClick = () => {
  // console.log('🔘 @click 事件被触发！');
  // console.log('🔘 直接调用submitFeedback函数');
  submitFeedback();
};

const handleSubmitTap = () => {
  // console.log('🔘 @tap 事件被触发！');
  // console.log('🔘 直接调用submitFeedback函数');
  submitFeedback();
};

// 测试按钮事件
// const testClick = () => {
//   console.log('🧪 测试按钮 @click 事件被触发！');
//   uni.showToast({ title: '测试按钮点击成功', icon: 'success' });
// };

// const testTap = () => {
//   console.log('🧪 测试按钮 @tap 事件被触发！');
//   uni.showToast({ title: '测试按钮点击成功', icon: 'success' });
// };

const submitFeedback = async () => {
  // console.log('=== 提交反馈调试信息开始 ===');
  // console.log('1. submitFeedback 函数被调用');
  // console.log('2. 当前时间:', new Date().toLocaleString());
  // console.log('3. canSubmit.value:', canSubmit.value);
  // console.log('4. submitting.value:', submitting.value);
  // console.log('5. feedbackType.value:', feedbackType.value);
  // console.log('6. feedbackTypeIndex.value:', feedbackTypeIndex.value);
  // console.log('7. content.value:', content.value);
  // console.log('8. content.value.trim().length:', content.value.trim().length);
  // console.log('9. images.value:', images.value);
  // console.log('10. contact.value:', contact.value);
  // console.log('11. userStore.isLoggedIn:', userStore.isLoggedIn);
  // console.log('12. userStore.profile:', userStore.profile);
  
  if (!canSubmit.value) {
    // console.log('❌ 提交被阻止：canSubmit 为 false');
    // console.log('❌ 原因分析:');
    // console.log('   - submitting:', submitting.value);
    // console.log('   - feedbackType:', feedbackType.value);
    // console.log('   - contentLength:', content.value.trim().length);
    errorMsg.value = '请填写完整反馈信息（内容不少于10字）';
    // console.log('=== 提交反馈调试信息结束 ===');
    return;
  }
  if (hasSensitiveWords(content.value)) {
    // console.log('❌ 提交被阻止：包含敏感词');
    errorMsg.value = '反馈内容包含敏感词，请修改后再提交。';
    // console.log('=== 提交反馈调试信息结束 ===');
    return;
  }
  // console.log('✅ 开始提交流程');
  submitting.value = true;
  errorMsg.value = '';
  successMsg.value = '';
  
  try {
    // 获取用户ID（如果已登录）
    const userId = userStore.isLoggedIn ? userStore.profile.uid : null;
    // console.log('13. 获取到的userId:', userId);
    
    // 映射反馈类型到后端格式
    const typeMapping = {
      '功能建议': 'feature',
      'BUG反馈': 'bug',
      '其他': 'other'
    };
    
    const feedbackData = {
      userId: userId,
      type: typeMapping[feedbackType.value] || 'other',
      content: content.value.trim(),
      images: images.value,
      contact: contact.value.trim() || null
    };
    
    // console.log('14. 准备发送的数据:', feedbackData);
    // console.log('15. 映射后的type:', typeMapping[feedbackType.value] || 'other');

    // console.log('16. 开始调用后端API...');
    // 调用后端API
    const response = await request({
      url: '/feedback/submit',
      method: 'POST',
      data: feedbackData
    });
    
    // console.log('17. 后端API响应:', response);

    if (response.code === 200) {
      // console.log('✅ 提交成功');
      uni.showToast({ title: '反馈已提交，我们将尽快处理', icon: 'none' });
      // 清空表单
      content.value = '';
      feedbackTypeIndex.value = -1;
      contact.value = '';
      images.value = [];
      uni.removeStorageSync('feedbackDraft');
      textareaHeight.value = 40;
    } else {
      // console.log('❌ 提交失败:', response.message);
      errorMsg.value = response.message || '提交失败，请稍后重试';
    }
  } catch (e) {
    // console.log('❌ 提交反馈异常:', e);
    // console.log('❌ 异常详情:', e.message);
    // console.log('❌ 异常堆栈:', e.stack);
    errorMsg.value = '提交失败，请稍后重试';
  } finally {
    // console.log('18. 设置submitting为false');
    submitting.value = false;
    // console.log('=== 提交反馈调试信息结束 ===');
  }
};
</script>

<style scoped>
.feedback-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e3eafc 0%, #f5f7ff 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 1.2rem 2rem 1.2rem;
  overflow-y: auto;
  -ms-overflow-style: none;  /* IE/Edge */
  scrollbar-width: none;     /* Firefox */
}
.feedback-page::-webkit-scrollbar {
  display: none;             /* Chrome/Safari */
}
.feedback-header {
  width: 100%;
  max-width: 480px;
  height: 3.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin: 0 0 2rem 0;
  background: #1890FF;
  border-radius: 0 0 20px 20px;
  color: #fff;
  font-weight: bold;
  padding: 0 1rem;
  box-shadow: 0 2px 8px rgba(24,144,255,0.08);
}
.back-btn {
  position: absolute;
  left: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #fff;
  font-size: 1.15rem;
  font-weight: 400;
  cursor: pointer;
  padding: 0 0.7rem;
  height: 2.2rem;
  line-height: 2.2rem;
  border-radius: 8px;
  transition: background 0.2s;
  box-shadow: none;
  outline: none;
}
.back-btn:active,
.back-btn:focus {
  background: rgba(255,255,255,0.12);
}
.header-title {
  margin: 0 auto;
  font-size: 1.5rem;
  font-weight: 700;
  color: #fff;
  text-align: center;
}
.feedback-form {
  width: 100%;
  max-width: 480px;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 4px 24px rgba(74,144,226,0.10);
  padding: 2.5rem 1.5rem 2rem 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 2.2rem;
}
.form-group {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  margin-bottom: 1.7rem;
}
.label {
  font-size: 1rem;
  color: #333;
  font-weight: 500;
  display: flex;
  align-items: center;
}
.required {
  color: #e74c3c;
  font-size: 1.1em;
  margin-right: 0.3em;
}
.textarea-row {
  position: relative;
  margin-bottom: 0.7rem;
}
textarea {
  border: 1.5px solid #b0b6be;
  border-radius: 8px;
  padding: 0.7rem 0.9rem;
  font-size: 1rem;
  background: #f8f9fa;
  transition: border 0.2s, background 0.2s;
  resize: none;
  width: 100%;
  box-sizing: border-box;
  min-height: 80px;
  color: #333;
}
textarea:focus {
  border-color: #1890FF;
  background: #fff;
  outline: none;
}
.char-count {
  position: absolute;
  right: 1rem;
  bottom: 0.7rem;
  font-size: 0.95rem;
  color: #888;
  background: rgba(255,255,255,0.9);
  padding: 0.2rem 0.4rem;
  border-radius: 4px;
  z-index: 2;
  pointer-events: none;
}
.count-gray { color: #888; }
.count-green { color: #27ae60; }
.count-red { color: #e74c3c; }
.image-row {
  display: flex;
  align-items: center;
  gap: 0.2rem;
  margin-top: 0.5rem;
}
.add-image-label {
  font-size: 0.98rem;
  color: #666;
  margin-right: 0.2rem;
}
.upload-btn {
  background: none;
  border: none;
  cursor: pointer;
  font-size: 1.3rem;
  color: #4a90e2;
  margin-left: 0.2rem;
  padding: 0.2rem 0.5rem;
  border-radius: 6px;
  transition: background 0.2s;
}
.upload-btn:disabled {
  color: #ccc;
  cursor: not-allowed;
}
.upload-btn:active {
  background: #e3eafc;
}
.image-preview {
  display: flex;
  gap: 0.5rem;
  margin-top: 0.8rem;
}
.img-thumb {
  position: relative;
  width: 48px;
  height: 48px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
}
.img-thumb-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}
.remove-img {
  position: absolute;
  top: 2px;
  right: 4px;
  background: rgba(0,0,0,0.5);
  color: #fff;
  border-radius: 50%;
  width: 16px;
  height: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.95rem;
  cursor: pointer;
}
.input-icon-group {
  display: flex; align-items: center;
  border: 1.5px solid #b0b6be; border-radius: 8px;
  background: #f8f9fa;
  padding: 0 0.2rem;
  margin-top: 0.5rem;
  transition: border 0.2s, background 0.2s;
}
.input-icon-group:focus-within {
  border-color: #1890FF;
  background: #fff;
}
.input-icon { margin-left: 0.7rem; margin-right: 0.5rem; color: #bbb; font-size: 1.2em; }
.input-icon + input {
  border: none;
  background: transparent;
  flex: 1;
  font-size: 1rem;
  padding: 0.7rem 0.2rem;
  color: #333;
}
input:focus {
  outline: none;
  border: none;
}
.picker-view {
  padding: 0.7rem 0.9rem;
  background: #f8f9fa;
  border: 1.5px solid #b0b6be;
  border-radius: 8px;
  font-size: 1rem;
  color: #333;
  transition: border 0.2s;
}
.picker-view:focus {
  border-color: #1890FF;
}
.submit-btn {
  background: linear-gradient(90deg, #4f8cff 0%, #1fd1f9 100%);
  color: #fff;
  font-size: 1.1rem;
  font-weight: 700;
  border: none;
  border-radius: 2.5rem;
  padding: 0.55rem 0;
  margin-top: 0.7rem;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(79,140,255,0.10);
  transition: background 0.2s, box-shadow 0.2s, transform 0.1s;
  width: 50%;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
.submit-btn:disabled {
  background: #b2bec3;
  cursor: not-allowed;
}
.submit-btn:active {
  transform: scale(0.98);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.loading-dot {
  display: inline-block;
  width: 1em;
  height: 1em;
  border-radius: 50%;
  background: #fff;
  margin-right: 0.5em;
  animation: loading 1s infinite linear alternate;
}
@keyframes loading {
  0% { opacity: 0.5; }
  100% { opacity: 1; }
}
.success-msg {
  color: #27ae60;
  background: #eafaf1;
  border-radius: 8px;
  padding: 0.7rem 1rem;
  margin-top: 0.5rem;
  text-align: center;
  font-size: 1rem;
}
.error-msg {
  color: #e74c3c;
  background: #fff0f0;
  border-radius: 8px;
  padding: 0.7rem 1rem;
  margin-top: 0.5rem;
  text-align: center;
  font-size: 1rem;
}
@media (max-width: 600px) {
  .feedback-header, .feedback-form {
    max-width: 100vw;
    padding-left: 0.5rem;
    padding-right: 0.5rem;
  }
}
</style>
